package org.dormi.learn;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author : dormi330
 * @since : 22/04/18
 */
public class TestFuture<T> implements Future<T> {
    private final T value;
    private final Timer timer;
    private boolean cancel = false;
    private boolean done = false;
    private final long delay;
    private final long startTime;

    public TestFuture(T value, long delay) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                TestFuture.this.done = true;
            }
        };
        timer = new Timer(true);
        timer.schedule(timerTask, delay);
        startTime = System.currentTimeMillis();
        this.value = value;
        this.delay = delay;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        this.cancel = true;
        timer.cancel();
        return true;
    }

    public boolean isCancelled() {
        return cancel;
    }

    public boolean isDone() {
        return done;
    }

    public T get() throws InterruptedException, ExecutionException {
        while (!done) {
            try {
                timer.wait(delay - System.currentTimeMillis() + startTime);
            } catch (Exception e) {

            }
        }
        return value;
    }

    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        throw new RuntimeException("not support");
    }
}
